package net.thxjj.mobileServer.websocket;

import com.amazonaws.services.iot.client.AWSIotException;
import com.amazonaws.services.iot.client.AWSIotMqttClient;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import net.thxjj.mobileServer.service.IUserService;
import net.thxjj.mobileServer.util.sampleUtil.SampleUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.net.InetSocketAddress;
import java.util.logging.Logger;

@Service
public class WebsocketServer {
    public static AWSIotMqttClient awsIotClient;
    private Logger logger = Logger.getLogger(String.valueOf(this.getClass()));
    @Value("${netty.port}")
    private int port;

    @Autowired
    private IUserService userService;


    public void run() throws Exception{

        String clientEndpoint = SampleUtil.getConfig("clientEndpoint");
        String clientId = SampleUtil.getConfig("clientId");

        String certificateFile = SampleUtil.getConfig("certificateFile");
        String privateKeyFile = SampleUtil.getConfig("privateKeyFile");
        if (awsIotClient == null && certificateFile != null && privateKeyFile != null) {
            String algorithm = SampleUtil.getConfig("keyAlgorithm");
            SampleUtil.KeyStorePasswordPair pair = SampleUtil.getKeyStorePasswordPair(certificateFile, privateKeyFile, algorithm);

            awsIotClient = new AWSIotMqttClient(clientEndpoint, clientId, pair.keyStore, pair.keyPassword);
        }

        try {
            awsIotClient.connect();
        } catch (AWSIotException e) {
            e.printStackTrace();
        }


        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup wokerGroup = new NioEventLoopGroup();

        try{
            logger.info("启动了WebSocket");
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup,wokerGroup).channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new WebSocketChannelInitializer(userService));
            ChannelFuture channelFuture = serverBootstrap.bind(new InetSocketAddress(port)).sync();
            channelFuture.channel().closeFuture().sync();
        }finally {
            bossGroup.shutdownGracefully();
            wokerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception{

        new WebsocketServer().run();
    }
}
